/*
 * Copyright 2009 Cedric Priscal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android_serialport_api;


import android.os.Environment;

//import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;


public class SerialPort {
    static {
        try {
            System.loadLibrary("serial_port");
        } catch (Throwable e) {
            e.printStackTrace();
            String path = Environment.getDataDirectory() + "/data/com.snap.update/files/libserial_port.so";
//            Logger.e("static initializer: loadLibrary失败,load:" + path);
            System.load(path);
        }
    }

    /*
     * Do not remove or rename the field mFd: it is used by native method
     * close();
     */
    private FileDescriptor mFd;
    // 文件输入、输出流
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    /**
     * 获取串口
     *
     * @param device   串口号
     * @param baudrate 波特率
     * @param flags    标记位
     * @throws SecurityException 安全异常
     * @throws IOException       IO流异常
     */
    public SerialPort(File device, int baudrate, int flags)
            throws SecurityException, IOException {

        /* Check access permission */
        if (!device.canRead() || !device.canWrite()) {
            try {
                /* Missing read/write permission, trying to chmod the file */
                Process su;
                su = Runtime.getRuntime().exec("/system/xbin/su");
                String cmd = "chmod 777 " + device.getAbsolutePath() + "\n"
                        + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead()
                        || !device.canWrite()) {
                    throw new SecurityException("串口异常1");
                }
            } catch (Exception e) {
                throw new SecurityException("串口异常2");
            }
        }

        mFd = open(device.getAbsolutePath(), baudrate, flags);
        if (mFd == null) {
            throw new IOException("未找到串口" + device.getPath());
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    // JNI
    private native static FileDescriptor open(String path, int baudrate, int flags);

    // Getters and setters
    public InputStream getInputStream() {
        return mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    public native void close();
}
